package com.newland.mesdk.demo.fragment;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.DeviceRTException;
import com.newland.mtype.ModuleType;
import com.newland.mtype.common.InnerProcessingCode;
import com.newland.mtype.common.ProcessingCode;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.cardreader.CommonCardType;
import com.newland.mtype.module.common.cardreader.OpenCardReaderEvent;
import com.newland.mtype.module.common.cardreader.OpenCardReaderResult;
import com.newland.mtype.module.common.emv.EmvTransInfo;
import com.newland.mtype.module.common.rfcard.RFCardType;
import com.newland.mtype.util.Dump;
import com.newland.mesdk.demo.event.SimpleTransferListener;
import com.newland.mesdk.demo.interfaceimpl.CardReaderInterfaceImpl;
import com.newland.mesdk.demo.interfaceimpl.QPBOCInterfaceImpl;
import com.newland.mesdk.demo.main.MainActivity;
import com.newland.mesdk.demo.main.MyApplication;
import com.newland.mesdk.demo.util.AppExCode;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.SharedPreferencesUtil;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * Created by YJF QPBOC模块
 */
public class QPBOCFragment extends Fragment implements OnClickListener {
	private MainActivity mainActivity;
	private QPBOCInterfaceImpl qpbocInterfaceImpl;
	private EditText edit_amt_input;
	private Button btn_sure, btn_cancel;
	private CharSequence temp;
	private BigDecimal amt;
	private Dialog amt_dialog;
	private String deviceType;
	private SimpleTransferListener simpleTransferListener;
	private Button btnEConsume, btnGetELog, btnGetEFunds;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_qpboc, null);
		mainActivity = (MainActivity) getActivity();
		deviceType = SharedPreferencesUtil.getStringParam(mainActivity, Const.DEVICETYPE);
		simpleTransferListener = new SimpleTransferListener(mainActivity, deviceType);
		initQPBOCView(view);
		return view;
	}

	public void initQPBOCView(View view) {
		btnEConsume = (Button) view.findViewById(R.id.btn_qpboc_econsume);
		btnEConsume.setOnClickListener(this);

		btnGetELog = (Button) view.findViewById(R.id.btn_qpboc_elog);
		btnGetELog.setOnClickListener(this);

		btnGetEFunds = (Button) view.findViewById(R.id.btn_qpboc_efunds);
		btnGetEFunds.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (mainActivity.isDeviceInit()) {
			if (mainActivity.processingisLocked()) {
				mainActivity.showMessage("请先完成或撤销当前操作...", MessageTag.ERROR);
			} else {
				mainActivity.connectDevice();
				qpbocInterfaceImpl = new QPBOCInterfaceImpl();
				final CardReaderInterfaceImpl cardReaderInterfaceImpl = new CardReaderInterfaceImpl();
				switch (v.getId()) {
				case R.id.btn_qpboc_econsume:
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							showInputAmoutDialog();

						}
					}).start();

					break;
				case R.id.btn_qpboc_efunds:
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								mainActivity.processingLock();
								try {
									cardReaderInterfaceImpl.openCardReader("请贴卡非接卡", new ModuleType[] {
											ModuleType.COMMON_SWIPER, ModuleType.COMMON_ICCARDREADER ,ModuleType.COMMON_RFCARDREADER}, new RFCardType[] {RFCardType.ACARD,RFCardType.BCARD,RFCardType.M1CARD}, true,
											true, 60, TimeUnit.SECONDS, new DeviceEventListener<OpenCardReaderEvent>() {
												@Override
												public void onEvent(OpenCardReaderEvent openCardReaderEvent,
														Handler handler) {
													if (openCardReaderEvent.isSuccess()) {
														mainActivity.showMessage("读卡器开启成功" + "\r\n", MessageTag.NORMAL);
														try {
															mainActivity.showMessage("请贴卡" + "\r\n", MessageTag.NORMAL);
															mainActivity.showMessage(" 开始电子现金余额查询(非接卡)" + "\r\n",
																	MessageTag.NORMAL);
															EmvTransInfo emvTransInfo = qpbocInterfaceImpl.startQPBOC(
																	ProcessingCode.GOODS_AND_SERVICE,
																	InnerProcessingCode.RF_EC_AVAILABLE_FUNDS_INQUIRY,
																	new BigDecimal("0"), 60, TimeUnit.SECONDS);
															if (emvTransInfo != null) {
																Integer resultCode = emvTransInfo.getExecuteRslt();
																if (resultCode == 0) {
																	mainActivity.showMessage("电子现金余额查询(非接卡)，成功！"
																			+ "\r\n", MessageTag.NORMAL);
																	mainActivity.processingUnLock();
																} else {
																	mainActivity.showMessage("电子现金余额查询(非接卡)，失败！"
																			+ "\r\n", MessageTag.NORMAL);
																	mainActivity.processingUnLock();
																}
																String cardFunds = emvTransInfo.getQpbocCardFunds();
																mainActivity.showMessage("电子现金余额查询(非接卡) 余额为:"
																		+ cardFunds + "\r\n", MessageTag.NORMAL);
																mainActivity.processingUnLock();
															} else {
																mainActivity.showMessage("QPBOC流程——电子现金余额查询(非接卡) 结果为空"
																		+ "\r\n", MessageTag.NORMAL);
																mainActivity.processingUnLock();
															}
														} catch (Exception e) {
															mainActivity.showMessage("电子现金余额查询(非接卡)异常：" + e + "\r\n",
																	MessageTag.ERROR);
															mainActivity.processingUnLock();
														}

													} else if (openCardReaderEvent.isUserCanceled()) {
														mainActivity.showMessage("取消开启读卡器" + "\r\n", MessageTag.NORMAL);
														mainActivity.processingUnLock();
													} else if (openCardReaderEvent.isFailed()) {
														mainActivity.showMessage("读卡器开启失败" + "\r\n", MessageTag.NORMAL);
														mainActivity.processingUnLock();
													}
												}

												@Override
												public Handler getUIHandler() {
													return null;
												}
											});
								} catch (Exception e) {
									mainActivity.showMessage("读卡器打开异常" + e + "\r\n", MessageTag.ERROR);
									mainActivity.processingUnLock();
								}

							} catch (Exception e) {
								e.printStackTrace();
								mainActivity.showMessage("读卡器开启失败" + e.getMessage() + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;
				case R.id.btn_qpboc_elog:
					new Thread(new Runnable() {

						@Override
						public void run() {
							mainActivity.processingLock();
							try {
								cardReaderInterfaceImpl.openCardReader("请贴卡非接卡", new ModuleType[] {
										ModuleType.COMMON_SWIPER, ModuleType.COMMON_ICCARDREADER ,ModuleType.COMMON_RFCARDREADER}, new RFCardType[] {RFCardType.ACARD,RFCardType.BCARD,RFCardType.M1CARD}, true, true,
										60, TimeUnit.SECONDS, new DeviceEventListener<OpenCardReaderEvent>() {
											@Override
											public void onEvent(OpenCardReaderEvent openCardReaderEvent, Handler handler) {
												if (openCardReaderEvent.isSuccess()) {
													mainActivity.showMessage("读卡器开启成功" + "\r\n", MessageTag.NORMAL);
													try {
														mainActivity.showMessage(" 开始电子现金日志(非接)" + "\r\n",
																MessageTag.NORMAL);
														EmvTransInfo emvTransInfo = qpbocInterfaceImpl.startQPBOC(
																ProcessingCode.GOODS_AND_SERVICE,
																InnerProcessingCode.RF_PBOC_LOGGER,
																new BigDecimal("0"), 60, TimeUnit.SECONDS);
														if (emvTransInfo.getEcashDetails() != null) {
															Integer resultCode = emvTransInfo.getExecuteRslt();
															if (resultCode == 0) {
																mainActivity.showMessage("获取电子现金日志(非接)，成功！" + "\r\n",
																		MessageTag.NORMAL);
																mainActivity.processingUnLock();
															} else {
																mainActivity.showMessage("获取电子现金日志(非接)，失败！" + "\r\n",
																		MessageTag.NORMAL);
																mainActivity.processingUnLock();
															}
															byte[] ecashDetails = emvTransInfo.getEcashDetails();
															mainActivity.showMessage(
																	"电子现金日志:" + Dump.getHexDump(ecashDetails) + "\r\n",
																	MessageTag.DATA);
															mainActivity.processingUnLock();
														} else {
															mainActivity.showMessage("该卡没有电子现金日志！" + "\r\n",
																	MessageTag.NORMAL);
															mainActivity.processingUnLock();
														}
													} catch (Exception e) {
														mainActivity.showMessage("电子现金日志(非接)异常：" + e + "\r\n",
																MessageTag.ERROR);
														mainActivity.processingUnLock();
													}
												} else if (openCardReaderEvent.isUserCanceled()) {
													mainActivity.showMessage("取消开启读卡器" + "\r\n", MessageTag.NORMAL);
													mainActivity.processingUnLock();
												} else if (openCardReaderEvent.isFailed()) {
													mainActivity.showMessage("读卡器开启失败" + "\r\n", MessageTag.NORMAL);
													mainActivity.processingUnLock();
												}
											}

											@Override
											public Handler getUIHandler() {
												return null;
											}
										});
							} catch (Exception e) {
								mainActivity.showMessage("读卡器打开异常" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						}
					}).start();

					break;

				default:
					break;
				}
			}
		} else {
			mainActivity.showMessage("设备未初始化，请先初始化！" + "\r\n", MessageTag.NORMAL);
		}
	}

	// 输入消费金额对话框
	public void showInputAmoutDialog() {
		mainActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mainActivity.processingLock();
				final CardReaderInterfaceImpl cardReaderInterfaceImpl = new CardReaderInterfaceImpl();
				final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mainActivity);
				LayoutInflater inflater = LayoutInflater.from(mainActivity);
				final View view = inflater.inflate(R.layout.dialog_amtinput, null);
				builder.setTitle("请输入交易金额（最高12位）:");
				edit_amt_input = (EditText) view.findViewById(R.id.edit_amt_input);
				btn_sure = (Button) view.findViewById(R.id.btn_sure);
				btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
				edit_amt_input.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
				builder.setView(view);
				edit_amt_input.addTextChangedListener(new TextWatcher() {
					@Override
					public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
						temp = arg0;
					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					}

					@Override
					public void afterTextChanged(Editable arg0) {
						if (temp.length() > 12) {
							btn_sure.setEnabled(false);
						} else {
							btn_sure.setEnabled(true);
						}

					}
				});

				btn_sure.setOnClickListener(new android.view.View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Editable editable = edit_amt_input.getText();
						try {
							DecimalFormat df = new DecimalFormat("#.00");
							amt = new BigDecimal(editable.toString());
							((MyApplication) mainActivity.getApplication()).setAmt(amt);
							mainActivity.showMessage("交易金额为:" + df.format(amt) + "\r\n", MessageTag.DATA);
							amt_dialog.dismiss();
							mainActivity.processingLock();
							try {
								cardReaderInterfaceImpl.openCardReader("请贴卡非接卡", new ModuleType[] {
										ModuleType.COMMON_SWIPER, ModuleType.COMMON_ICCARDREADER ,ModuleType.COMMON_RFCARDREADER}, new RFCardType[] {RFCardType.ACARD,RFCardType.BCARD,RFCardType.M1CARD}, true, true,
										60, TimeUnit.SECONDS, new DeviceEventListener<OpenCardReaderEvent>() {
											@Override
											public void onEvent(OpenCardReaderEvent openCardReaderEvent, Handler handler) {
												if (openCardReaderEvent.isSuccess()) {
													mainActivity.showMessage("读卡器开启成功" + "\r\n", MessageTag.NORMAL);
													try {
														mainActivity.showMessage("请贴卡" + "\r\n", MessageTag.NORMAL);
														mainActivity
																.showMessage("开始电子现金消费" + "\r\n", MessageTag.NORMAL);
														EmvTransInfo emvTransInfo = qpbocInterfaceImpl.startQPBOC(
																ProcessingCode.GOODS_AND_SERVICE,
																InnerProcessingCode.EC_CONSUMPTION, amt, 60,
																TimeUnit.SECONDS);
														if (emvTransInfo != null) {
															Integer resultCode = emvTransInfo.getExecuteRslt();
															mainActivity.showMessage("QPBOC流程——电子现金消费 结果码(0xDF75)为:"
																	+ resultCode + "\r\n", MessageTag.NORMAL);
															simpleTransferListener.onQpbocFinished(emvTransInfo);
														} else {
															mainActivity.showMessage("QPBOC流程——电子现金消费 结果为空" + "\r\n",
																	MessageTag.NORMAL);
														}

													} catch (Exception e) {
														mainActivity.showMessage("电子现金消费异常：" + e + "\r\n",
																MessageTag.ERROR);
														mainActivity.processingUnLock();
													}
												} else if (openCardReaderEvent.isUserCanceled()) {
													mainActivity.showMessage("取消开启读卡器" + "\r\n", MessageTag.NORMAL);
													mainActivity.processingUnLock();
												} else if (openCardReaderEvent.isFailed()) {
													mainActivity.showMessage("读卡器开启失败" + "\r\n", MessageTag.NORMAL);
													mainActivity.processingUnLock();
												}
											}

											@Override
											public Handler getUIHandler() {
												return null;
											}
										});
							} catch (Exception e) {
								mainActivity.showMessage("读卡器打开异常" + e + "\r\n", MessageTag.ERROR);
								mainActivity.processingUnLock();
							}

						} catch (Exception e) {
							mainActivity.showMessage("输入金额异常：" + e, MessageTag.ERROR);
							mainActivity.processingUnLock();
						}
					}
				});

				btn_cancel.setOnClickListener(new android.view.View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mainActivity.showMessage("交易取消" + "\r\n", MessageTag.NORMAL);
						amt_dialog.dismiss();
						mainActivity.processingUnLock();
					}
				});
				amt_dialog = builder.create();
				amt_dialog.show();
				amt_dialog.setCanceledOnTouchOutside(false);
			}
		});
	}

}
